package com.share.finance.asset.sjd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.utils.IdCardUtil;
import com.share.common.utils.ThreadUtil;
import com.share.finance.asset.sjd.mapper.UserBindCardMapper;
import com.share.finance.asset.sjd.mapper.UserInfoMapper;
import com.share.finance.asset.sjd.model.db.UserBindCard;
import com.share.finance.asset.sjd.model.db.UserFile;
import com.share.finance.asset.sjd.model.db.UserInfo;
import com.share.finance.asset.sjd.model.vo.BindCardVo;
import com.share.finance.asset.sjd.service.IUserBindCardService;
import com.share.finance.asset.sjd.service.IUserFileService;
import com.share.finance.asset.sjd.service.IUserInfoService;
import com.share.finance.risk.common.enums.FileTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户绑卡信息  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-09-08
 */
@Service
public class UserBindCardServiceImpl extends ServiceImpl<UserBindCardMapper, UserBindCard> implements IUserBindCardService {
    @Resource
    private UserBindCardMapper userBindCardMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private IUserFileService userFileService;
    @Autowired
    private IUserInfoService userInfoService;

    @Override
    public int bindCard(BindCardVo req) {
        //用户信息处理
        UserInfo userInfo = saveOrUpdateUser(req);

        //绑卡
        saveOrUpdateBindCard(req, userInfo);

        //文件数据提取
        saveOrUpdateUserFile(req, userInfo);

        return 1;
    }

    //用户信息保存
    private UserInfo saveOrUpdateUser(BindCardVo req) {
        UserInfo user = userInfoService.getByIdCard(req.getIdCard());
        if (user == null) {
            //创建一个新用户
            String idCard = req.getIdCard();
            user = new UserInfo();
            user.setUserId(System.currentTimeMillis() + "");
            user.setIdCardNo(idCard);
            user.setUserName(req.getName());
            user.setPhoneNo(req.getPhoneNo());
            user.setSex(IdCardUtil.getSex(idCard));
            user.setBirthDate(IdCardUtil.getBirthDay(idCard));
            user.setIdCardAddress(req.getAddress());
            user.setUserStatus("1");
            user.setCreateTime(new Date());
            int insert = userInfoMapper.insert(user);
        } else {
            //更新用户信息
            UserInfo userUpdate = new UserInfo();
            userUpdate.setId(user.getId());
            userUpdate.setUpdateTime(new Date());
            int insert = userInfoMapper.updateById(user);

            user.setUpdateTime(userUpdate.getUpdateTime());
        }
        return user;
    }

    //用户绑卡
    private void saveOrUpdateBindCard(BindCardVo req, UserInfo userInfo) {
        String userId = userInfo.getUserId();
        ThreadUtil.execute(() -> {
            UserBindCard tmpRecord = getByUserIdAndBizCode(userId, req.getProductCode());
            if (tmpRecord == null) {
                //绑卡
                UserBindCard bindCard = new UserBindCard();
                bindCard.setUserId(userInfo.getUserId());
                bindCard.setBankCardNo(req.getBankCard());
                bindCard.setBusinessCode(req.getProductCode());
                bindCard.setHolderCardName(req.getName());
                bindCard.setStatus("1");
                bindCard.setCreateTime(new Date());
                userBindCardMapper.insert(bindCard);
            } else {
                //更新信息
                UserBindCard updateBindCard = new UserBindCard();
                updateBindCard.setId(tmpRecord.getId());
                updateBindCard.setUpdateTime(new Date());
                userBindCardMapper.updateById(updateBindCard);
            }
        });
    }

    //用户文件保存
    private void saveOrUpdateUserFile(BindCardVo req, UserInfo userInfo) {
        List<UserFile> listUserFile = new LinkedList<>();
        String userId = userInfo.getUserId();
        String bizCode = req.getProductCode();
        ThreadUtil.execute(() -> {
            UserFile userFile1 = createOneUserFile(userId, bizCode, req.getIdCardBackImage(), FileTypeEnum.ID_CARD_BACK.getType());
            if (userFile1 != null) {
                listUserFile.add(userFile1);
            }

            UserFile userFile2 = createOneUserFile(userId, bizCode, req.getIdCardFrontImage(), FileTypeEnum.ID_CARD_FRONT.getType());
            if (userFile2 != null) {
                listUserFile.add(userFile2);
            }

            UserFile userFile3 = createOneUserFile(userId, bizCode, req.getPersonAuthorizationFile(), FileTypeEnum.PERSON_AUTHORIZATION_FILE.getType());
            if (userFile3 != null) {
                listUserFile.add(userFile3);
            }

            if (!CollectionUtils.isEmpty(listUserFile)) {
                userFileService.saveBatch(listUserFile);
            }
        });
    }

    //创建一个文件
    private UserFile createOneUserFile(String userId, String bizCode, String imageUrl, String imageTypeCode) {
        UserFile userFile = null;
        if (StringUtils.isNotBlank(imageUrl)) {
            userFile = new UserFile();
            userFile.setUserId(userId);
            userFile.setBusinessCode(bizCode);
            userFile.setIsDelete("0");
            userFile.setCreateTime(new Date());
            userFile.setFileUrl(imageUrl);
            userFile.setFileType(imageTypeCode);
        }
        return userFile;
    }

    //获取某个业务的绑卡信息
    @Override
    public UserBindCard getByUserIdAndBizCode(String userId, String bizCode) {
        LambdaQueryWrapper<UserBindCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBindCard::getUserId, userId);
        queryWrapper.eq(UserBindCard::getBusinessCode, bizCode);
        queryWrapper.eq(UserBindCard::getStatus, "1");
        UserBindCard userBindCard = userBindCardMapper.selectOne(queryWrapper);
        return userBindCard;
    }

    @Override
    public List<UserBindCard> listByUserId(String userId, String bizCode) {
        List<UserBindCard> reList = null;

        List<String> list = new LinkedList<>();
        list.add(userId);
        Map<String, List<UserBindCard>> tmpMap = listByUserIds(list, bizCode);
        if (!CollectionUtils.isEmpty(tmpMap)) {
            reList = tmpMap.get(userId);
        }
        return reList;
    }

    @Override
    public Map<String, List<UserBindCard>> listByUserIds(List<String> userIdList, String bizCode) {
        LambdaQueryWrapper<UserBindCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserBindCard::getUserId, userIdList);
        if (StringUtils.isNotBlank(bizCode)) {
            queryWrapper.eq(UserBindCard::getBusinessCode, bizCode);
        }
        queryWrapper.eq(UserBindCard::getStatus, "1");

        List<UserBindCard> list = userBindCardMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            Map<String, List<UserBindCard>> reMap = list.stream().filter(f -> StringUtils.isNotBlank(f.getUserId())).collect(Collectors.groupingBy(e -> e.getUserId()));
            return reMap;
        }
    }
}
